package msg_push

import (
	"github.com/mitchellh/mapstructure"
	"im_sys/apps/im/ws/internal/svc"
	"im_sys/apps/im/ws/ws_server"
	"im_sys/apps/im/ws/ws_struct"
)

// PushToReceiver websocket服务端将消息转发给接收方
func PushToReceiver(svc *svc.ServiceContext) ws_server.HandlerFunc {
	return func(server *ws_server.Server, conn *ws_server.WSKeepAlive, msg *ws_server.Message) {
		var data *ws_struct.PushMsg
		if err := mapstructure.Decode(msg.Data, &data); err != nil {
			_ = server.Send(ws_server.NewErrorMessage(err), conn)
			return
		}

		// 获取kafka的websocket连接
		recvConn := server.GetConnByUid(data.RecvId)
		if recvConn == nil {
			// todo: 用户离线
			return
		}

		server.Infof("push msg to kafka %v", data)

		_ = server.Send(ws_server.NewMessage(data.SendId, &ws_struct.Chat{
			ConversationId: data.ConversationId,
			ChatType:       data.ChatType,
			SendTime:       data.SendTime,
			Msg: ws_struct.Msg{
				MType:   data.MType,
				Content: data.Content,
			},
		}), recvConn...)
	}
}
